package fw_db_erp

import (
	"fmt"
	"gorm.io/driver/sqlserver"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"sync"
	"time"
	"wms-server/fw/fw_config"
)

var (
	db   *gorm.DB
	once sync.Once
)

func InitDB() {
	once.Do(func() {
		var err error
		dsn := "sqlserver://" + fw_config.GetConfigHandler().GetString("db.erp.user") + ":" + fw_config.GetConfigHandler().GetString("db.erp.pwd") +
			"@" + fw_config.GetConfigHandler().GetString("db.erp.host") + ":" + fw_config.GetConfigHandler().GetString("db.erp.port") + "?database=" + fw_config.GetConfigHandler().GetString("db.wms.dbname") + "&encrypt=DISABLE"
		db, err = gorm.Open(sqlserver.Open(dsn), &gorm.Config{
			SkipDefaultTransaction: true,
			NamingStrategy:         schema.NamingStrategy{SingularTable: true},
			Logger:                 logger.Default.LogMode(logger.Info),
		})
		if err == nil {
			fmt.Println("数据库打开成功")
		} else {
			fmt.Println("数据库打开失败")
			return
		}
		sqlDB, err := db.DB()
		if err != nil {
			fmt.Println("通用数据库对象获取失败")
			return
		}
		sqlDB.SetMaxOpenConns(100)
		sqlDB.SetMaxIdleConns(100)
		sqlDB.SetConnMaxIdleTime(time.Hour)
	})
}

func GetSqlserverDB() *gorm.DB {
	return db
}
